import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>
  ) { }

  create(createUserDto: CreateUserDto) {
    return this.userRepository.save(createUserDto);
  }

  findAll() {
    return `This action returns all user`;
  }

  async findOne(user_name: string): Promise<User | undefined> {
    return await this.userRepository.findOne({ where: { user_name } });
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }

  async getInfo(id: number) {
    const { name, introduction, avatar, role } = await this.userRepository.findOne({ relations: ["role"], where: { id } });
    return {
      code: 200,
      data: {
        name,
        roles: [role.role_name],
        routes: JSON.parse(role.routes),
        introduction,
        avatar
      }
    }
  }

  logout(id: number) {
    return {
      code: 200,
      data: 'success'
    }
  }

}
